package com.atguigu.gulimall.search.Service.imp;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.Service.MallSearchService;
import com.atguigu.gulimall.search.config.GulimallElasticsearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import javafx.beans.binding.ObjectExpression;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.apache.tomcat.util.security.Escape;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.Highlighter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    RestHighLevelClient client;

    /**
     * 根据检索条件，从ES中检索数据
     *
     * @param searchParam 检索条件
     * @return
     */
    @Override
    public SearchResult search(SearchParam searchParam) {
        SearchResult result = null;

        //动态构建出查询需要的DSL语句
        //①、准备检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        try {
            //②、执行检索请求
            SearchResponse response = client.search(searchRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);

            //③、分析响应数据，封装成我们需要的格式
            result = buildSearchResult(response, searchParam);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 构建检索请求
     * 模糊匹配、过滤(按照属性、分类、品牌、价格区间、库存)，排序、分页、高亮，聚合分析
     *
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        //构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /**
         * 查询：模糊匹配、过滤(按照属性、分类、品牌、价格区间、库存)
         */
        //1、构建bool-query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1、must-模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword()))
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        //1.2、filter-过滤
        //1.2.1、按照三级分类id过滤
        if (param.getCatalog3Id() != null)
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        //1.2.2、按照品牌id过滤
        if (param.getBrandId() != null && param.getBrandId().size() > 0)
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        //1.2.3、按照是否有库存过滤
        if (param.getHasStock() != null)
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        //1.2.4、按照价格区间过滤
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            //1_500/_500/500_
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 1 && param.getSkuPrice().endsWith("_")) {
                rangeQuery.gte(s[0]);
            } else {
                if (param.getSkuPrice().indexOf("_") == 0) {
                    rangeQuery.lte(s[1]);
                } else {
                    rangeQuery.gte(s[0]).lte(s[1]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        //1.2.5、按照属性进行过滤
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            //attrs=1_5寸:8寸&attrs=2_8G&12G
            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                //attrStr = 1_5寸:8寸
                String[] s = attrStr.split("_");
                String attrId = s[0];//检索的属性id
                String[] attrValues = s[1].split(":");//检索的属性值（多个）
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                //每一个必须都得生成一个nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        //查询构建完成
        sourceBuilder.query(boolQuery);


        /**
         * 排序、分页、高亮
         */
        //2.1、排序
        if (!StringUtils.isEmpty(param.getSort())) {
            //sort=hotScore_asc/desc
            String[] s = param.getSort().split("_");
            SortOrder asc = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            //排序构建完成
            sourceBuilder.sort(s[0], asc);
        }

        //2.2、分页
        int pageSize = EsConstant.PRODUCT_PAGESIZE;
        int pageNum = (param.getPageNum() - 1) * pageSize;
        //分页构建完成
        sourceBuilder.from(pageNum);
        sourceBuilder.size(pageSize);

        //2.3、高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            //高亮构建完成
            sourceBuilder.highlighter(builder);
        }


        /**
         * 聚合分析
         */
        //3.1、品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //3.1.1、品牌聚合的两个子聚合
        //3.1.2、品牌名字
        TermsAggregationBuilder brandName_agg = AggregationBuilders.terms("brandName_agg").field("brandName").size(1);
        brand_agg.subAggregation(brandName_agg);
        //3.1.3、品牌图片
        TermsAggregationBuilder brandImg_agg = AggregationBuilders.terms("brandImg_agg").field("brandImg").size(1);
        brand_agg.subAggregation(brandImg_agg);
        //品牌聚合构建完成
        sourceBuilder.aggregation(brand_agg);

        //3.2、分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        //3.2.1、分类聚合的子聚合
        //3.2.2、分类名字
        TermsAggregationBuilder catalogName_agg = AggregationBuilders.terms("catalogName_agg").field("catalogName").size(1);
        catalog_agg.subAggregation(catalogName_agg);
        //分类聚合构建完成
        sourceBuilder.aggregation(catalog_agg);

        //3.3、属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        //聚合分析出当前attr_id对应的attrName
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //聚合分析出当前attr_id对应的所有的attrValue
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        //属性聚合构建完成
        sourceBuilder.aggregation(attr_agg);


        System.out.println("构建出来的DSL语句：" + sourceBuilder.toString());

        //封装：检索请求
        //参数一：指定要检索的索引
        //参数二：构建好的DSL语句
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);

        return searchRequest;
    }

    /**
     * 构建结果数据
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam searchParam) {
        SearchResult result = new SearchResult();

        //1、返回所有查询到的商品信息
        //获取命中的记录
        SearchHits hits = response.getHits();
        ArrayList<SkuEsModel> sku_list = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0)
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel sku = JSON.parseObject(sourceAsString, SkuEsModel.class);
                //设置高亮信息
                if (!StringUtils.isEmpty(searchParam.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    sku.setSkuTitle(string);
                }
                sku_list.add(sku);
            }
        result.setProducts(sku_list);

        //2、当前所有商品涉及到的所有属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
            //得到属性的name
            String attr_name = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            //得到属性的所有value
            List<String> attr_values = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = ((Terms.Bucket) item).getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attr_name);
            attrVo.setAttrValue(attr_values);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        //3、当前所有商品涉及到的所有品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //品牌的id
            long brand_id = bucket.getKeyAsNumber().longValue();
            //品牌的name
            String brand_name = ((ParsedStringTerms) bucket.getAggregations().get("brandName_agg")).getBuckets().get(0).getKeyAsString();
            //品牌的img
            String brand_img = ((ParsedStringTerms) bucket.getAggregations().get("brandImg_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brand_id);
            brandVo.setBrandName(brand_name);
            brandVo.setBrandImg(brand_img);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        //4、当前所有商品涉及到的所有分类信息
        ArrayList<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> catalog_aggBuckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : catalog_aggBuckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //得到分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));
            //得到分类name
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalogName_agg");
            String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalog_name);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

//        ==========以上从聚合信息中获取=========

        //5、分页信息-当前页码
        result.setPageNum(searchParam.getPageNum());
        //5.1、分页信息-总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //5.2、分页信息-总页数
        int totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE : (int) (total / EsConstant.PRODUCT_PAGESIZE) + 1;
        result.setTotalPages(totalPages);
        //5.3、分页信息-页码条
        List<Integer> pageNvs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNvs.add(i);
        }
        result.setPageNavs(pageNvs);

        //6、面包屑导航功能
        //6.1、属性的面包屑导航
        List<String> attrs = searchParam.getAttrs();
        if (attrs != null && attrs.size() > 0) {
            List<SkuEsModel.Attrs> attrs1 = sku_list.get(0).getAttrs();//任意一个skuModel都包含需要的attrs
            List<SkuEsModel.Attrs> finalAttrs = attrs1;
            List<SearchResult.NavVo> collect = searchParam.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                //10_天机
                String[] s = attr.split("_");
                //s[0]是attrId,根据当前attrId，从response中获取对应的attrName
                for (SkuEsModel.Attrs attrs2 : finalAttrs) {
                    if (StringUtils.equals(attrs2.getAttrId().toString(), s[0])) {
                        navVo.setNavName(attrs2.getAttrName());
                    }
                }
                //s[1]就是value值
                navVo.setNavValue(s[1]);
                //6.1、取消了这个面包屑以后，我们要跳转到那个地方，将请求地址的url里面的当前属性置空
                //拿到所有的查询条件，去掉当前
                String replace = getNavLink(searchParam, attr, "attrs");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
                result.getNavIds().add(Long.valueOf(s[0]));
                return navVo;
            }).collect(Collectors.toList());
            result.getNavs().addAll(collect);
        }

        //6.2、品牌的面包屑导航
        //brandId=27
        List<Long> brandId = searchParam.getBrandId();
        if (brandId != null && brandId.size() > 0) {
            SkuEsModel skuEsModel = sku_list.get(0);
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");
            navVo.setNavValue(skuEsModel.getBrandName());
            navVo.setLink("http://search.gulimall.com/list.html?" + getNavLink(searchParam, searchParam.getBrandId().get(0).toString(), "brandId"));
            result.getNavs().add(navVo);
        }

        //6.3、分类的面包屑导航


        return result;
    }


    public String getNavLink(SearchParam searchParam, String attr, String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(attr, "UTF-8");
            encode = encode.replace("+", "%20");//浏览器和java编码存在差异
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (searchParam.get_queryString().indexOf("&") == 0) {
            return searchParam.get_queryString().replace("&" + key + "=" + encode, "");
        } else {
            String replace = searchParam.get_queryString().replaceFirst(key + "=" + encode, "");
            return replace.replace("&" + key + "=" + encode, "");

        }
    }


}
